﻿/*
    Copyright (c) 2008 - 2009, Carlos Guzmán Álvarez

    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, 
    are permitted provided that the following conditions are met:

        * Redistributions of source code must retain the above copyright notice, 
          this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright notice, 
          this list of conditions and the following disclaimer in the documentation and/or 
          other materials provided with the distribution.
        * Neither the name of the author nor the names of its contributors may be used to endorse or 
          promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows.Threading;
using Microsoft.Practices.Composite;
using Microsoft.Practices.Unity;

namespace XClient.Infrastructure
{
    /// <summary>
    /// Base class for ViewModel implementations
    /// </summary>
    /// <typeparam name="TDataModel"></typeparam>
    /// <remarks>Model-View-ViewModel pattern</remarks>
    public abstract class ViewModel<TDataModel> : IHeaderInfoProvider, IDataErrorInfo, INotifyPropertyChanged, IActiveAware
    {
        #region · Static Metadata Members ·

        /// <value>Cache of derived types property meta data. This meta data is used for notify property changes</value>
        protected static Dictionary<Type, List<PropertyInfo>> PropertyMetaData = new Dictionary<Type, List<PropertyInfo>>();

        #endregion

        #region · INotifyPropertyChanged Events ·

        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region · IActiveAware Events ·

        event EventHandler IActiveAware.IsActiveChanged
        {
            add { throw new NotImplementedException(); }
            remove { throw new NotImplementedException(); }
        }

        #endregion

        #region · Fields ·

        private TDataModel  dataModel;
        private Dispatcher  dispatcher;
        private bool        isActive;

        #endregion

        #region · IHeaderInfoProvider Properties ·

        /// <summary>
        /// Gets the header info.
        /// </summary>
        /// <value>The header info.</value>
        /// <remarks>
        /// To provider a header description to CompositeWPF regions.
        /// </remarks>
        public abstract string HeaderInfo
        {
            get;
        }

        #endregion

        #region · IDataErrorInfo Members ·

        public string Error
        {
            get { return null; }
        }

        public string this[string columnName]
        {
            get { return null; }
        }

        #endregion

        #region · IActiveAware Properties ·

        /// <summary>
        /// Gets a value that indicates if the view model is active.
        /// </summary>
        public bool IsActive
        {
            get { return this.isActive; }
            set
            {
                this.isActive = value;
                this.ActivateCommands();
            }
        }

        #endregion

        #region · Protected Properties ·

        /// <summary>
        /// Gets the dispatcher.
        /// </summary>
        /// <value>The dispatcher.</value>
        protected Dispatcher Dispatcher
        {
            get { return dispatcher; }
        }

        /// <summary>
        /// Gets the data model.
        /// </summary>
        /// <value>The data model.</value>
        protected TDataModel DataModel
        {
            get { return this.dataModel; }
            set { this.dataModel = value; }
        }

        #endregion

        #region · Constructors ·

        /// <summary>
        /// Initializes a new instance of the <see cref="ViewModel"/> class.
        /// </summary>
        protected ViewModel()
        {
            this.InitializeMetaData(typeof(ViewModel<TDataModel>));
            this.dispatcher = Dispatcher.CurrentDispatcher;
        }

        #endregion

        #region · Protected Methods ·

        /// <summary>
        /// Notifies the property changed.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        protected virtual void NotifyPropertyChanged(String propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// Notifies all properties changed.
        /// </summary>
        protected virtual void NotifyAllPropertiesChanged()
        {
            VerifyCalledOnUIThread();

            PropertyMetaData[this.GetType()].ForEach(delegate(PropertyInfo pi)
            {
                this.NotifyPropertyChanged(pi.Name);
            });
        }

        /// <summary>
        /// Verifies if a given call was made from the UI thread
        /// </summary>
        [Conditional("Debug")]
        protected virtual void VerifyCalledOnUIThread()
        {
            Debug.Assert(Dispatcher.CurrentDispatcher == this.Dispatcher, "Call must be made on UI thread.");
        }

        /// <summary>
        /// Initializes type metadata
        /// </summary>
        /// <param name="baseType"></param>
        protected virtual void InitializeMetaData(Type baseType)
        {
            Type thisType = GetType();

            if (!PropertyMetaData.ContainsKey(thisType))
            {
                List<PropertyInfo> excludeList = new List<PropertyInfo>(
                    baseType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance));

                Type deriveType = this.GetType();

                List<PropertyInfo> includeList = new List<PropertyInfo>(
                    deriveType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance));

                includeList.RemoveAll(delegate(PropertyInfo pi)
                {
                    // Exclude base type and readonly properties
                    return excludeList.Contains(pi) || !pi.CanWrite;
                });

                PropertyMetaData.Add(thisType, includeList);
            }
        }

        #endregion

        #region · Command MEthods ·

        /// <summary>
        /// Initializes the commands.
        /// </summary>
        protected virtual void InitializeCommands()
        {
        }

        /// <summary>
        /// Registers the commands.
        /// </summary>
        protected virtual void RegisterCommands()
        {
        }

        /// <summary>
        /// Activates the commands
        /// </summary>
        protected virtual void ActivateCommands()
        {
        }

        #endregion
    }
}